package main

import (
	"context"
	"encoding/json"
	"fmt"
	"strings"

	"github.com/elastic/go-elasticsearch/v8"
	"github.com/elastic/go-elasticsearch/v8/esapi"
	"github.com/flipped-aurora/gin-vue-admin/server/core"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/initialize"
	"github.com/flipped-aurora/gin-vue-admin/server/model/products"
	"github.com/redis/go-redis/v9"
	_ "go.uber.org/automaxprocs"
	"go.uber.org/zap"
)

//go:generate go env -w GO111MODULE=on
//go:generate go env -w GOPROXY=https://goproxy.cn,direct
//go:generate go mod tidy
//go:generate go mod download

// 这部分 @Tag 设置用于排序, 需要排序的接口请按照下面的格式添加
// swag init 对 @Tag 只会从入口文件解析, 默认 main.go
// 也可通过 --generalInfo flag 指定其他文件
// @Tag.Name        Base
// @Tag.Name        SysUser
// @Tag.Description 用户

// @title                       Gin-Vue-Admin Swagger API接口文档
// @version                     v2.8.5
// @description                 使用gin+vue进行极速开发的全栈开发基础平台
// @securityDefinitions.apikey  ApiKeyAuth
// @in                          header
// @name                        x-token
// @BasePath                    /
func main() {
	// 初始化系统
	initializeSystem()
	// 运行服务器
	core.RunServer()
}

// initializeSystem 初始化系统所有组件
// 提取为单独函数以便于系统重载时调用
func initializeSystem() {
	global.GVA_VP = core.Viper() // 初始化Viper
	initialize.OtherInit()
	global.GVA_LOG = core.Zap() // 初始化zap日志库
	zap.ReplaceGlobals(global.GVA_LOG)
	global.GVA_DB = initialize.Gorm() // gorm连接数据库
	initialize.Timer()
	initialize.DBList()
	initialize.SetupHandlers() // 注册全局函数
	if global.GVA_DB != nil {
		initialize.RegisterTables() // 初始化表
	}
	MyInit()
}
func MyInit() {
	ESConn()
	RedisConn()
}

func RedisConn() {
	global.Redis = redis.NewClient(&redis.Options{
		Addr:     "14.103.158.217:6379",
		Password: "redis_x3jTtC",
		DB:       0,
	})
}

func ESConn() {
	global.ES, _ = elasticsearch.NewClient(elasticsearch.Config{
		Addresses: []string{"http://14.103.158.217:9200"},
	})
	BuildIndex()
	InsertIntoEs()
}

func BuildIndex() {
	request := esapi.IndicesCreateRequest{Index: "products"}
	do, err := request.Do(context.Background(), global.ES)
	fmt.Println(do, err)
	if err != nil {
		panic("build index fail")
	}
}
func InsertIntoEs() {
	var produceses []products.ProductData
	db := global.GVA_DB.Model(&products.Product{})
	db = db.Joins("join brand on product.brand_id = brand.brand_id")
	db = db.Joins("join category on product.category_id = category.category_id")
	db = db.Select("product.*,brand.brand_name as brand,category.category_name as category")
	db.Find(&produceses)
	for _, producese := range produceses {
		data, _ := json.Marshal(producese)
		esapi.IndexRequest{
			Index:      "products",
			DocumentID: fmt.Sprintf("%d", *producese.ProductId),
			Body:       strings.NewReader(string(data)),
			Refresh:    "true",
		}.Do(context.Background(), global.ES)
	}
}
